# Static resource management blueprint

from flask import Blueprint, request, send_from_directory, jsonify
from flask_cors import CORS
from database.postgre_singleton import PostgreSingleton
from database.device_info_table_methods import DeviceInfoTableMethods
import psycopg2.extras
import os
import logging

static_resource_bp = Blueprint('static_resource', __name__)
CORS(static_resource_bp)  # 允许跨域请求

# 设置静态资源存储目录
UPLOAD_FOLDER = 'uploads'
if not os.path.exists(UPLOAD_FOLDER):
    os.makedirs(UPLOAD_FOLDER)


def allowed_file(filename):
    # csv文件后缀名
    return '.' in filename and filename.rsplit('.', 1)[1].lower() in ['csv']

# 上传文件接口
@static_resource_bp.route('/upload', methods=['POST'])
def upload_file():

    if 'file' not in request.files:
        return jsonify({
            "status": -1,
            "errorCode": 1000,
            "errorMsg": "No file part",
            "resultBody": None
        })
    file = request.files['file']

    if file.filename == '':
        # return jsonify({'error': 'No selected file'}), 400

        return jsonify({
            "status": -1,
            "errorCode": 1001,
            "errorMsg": "No selected file",
            "resultBody": None
        })
    
    if not file:

        return jsonify({
            "status": -1,
            "errorCode": 1004,
            "errorMsg": "File not found",
            "resultBody": None
        })
    
    elif not allowed_file(file.filename):
        return jsonify({
            "status": -1,
            "errorCode": 1005,
            "errorMsg": "File type not allowed",
            "resultBody": None
        })
    
    # 文档大小限制不超过1M
    elif file.content_length > 1024 * 1024:
        return jsonify({
            "status": -1,
            "errorCode": 1002,
            "errorMsg": "File size exceeds 1M",
            "resultBody": None
        })
    
    elif file.filename in os.listdir(UPLOAD_FOLDER):
        return jsonify({
            "status": -1,
            "errorCode": 1003,
            "errorMsg": "File already exists",
            "resultBody": None
        })
    
    else:
        # 读取CSV文件内容
        csv_content = file.read().decode('utf-8')
        # 处理CSV文件内容
        insert_params = []

        for line in csv_content.split('\n'):
            try:
                device_mac, device_type = line.split(',')
            except Exception as e:
                logging.error(f"Failed to parse line: {line}, error: {e}")

            else:
                if device_mac == '' or device_type == '' or device_mac=="device_mac" or device_type =="device_type":
                    continue
                insert_params.append((device_mac, device_type))

        # 插入数据库
        logging.info(f"Insert {len(insert_params)} device info records into database")
        logging.debug(f"Insert params: {insert_params}")
        with PostgreSingleton() as conn:
            cur = conn.cursor(cursor_factory=psycopg2.extras.RealDictCursor) # cursor for executing queries

            DeviceInfoTableMethods(conn, cur).insert_device_info_list(insert_params)

        # 保存文件到指定目录
        filename = os.path.join(UPLOAD_FOLDER, file.filename)
        try:
            file.seek(0)
            file.save(filename)

        except Exception as e:
            file.close()
            return jsonify({
                "status": -1,
                "errorCode": 1006,
                "errorMsg": f"Failed to save file: {e}",
                "resultBody": None
            })
        else:

            file.close()
            # return jsonify({'message': f'File uploaded successfully: {file.filename}'}), 201
        return jsonify({
            "status": 1,
            "errorCode": None,
            "errorMsg": None,
            "resultBody": f"File uploaded successfully: {file.filename}"
        })

# 下载文件接口
@static_resource_bp.route('/download/<filename>', methods=['GET'])
def download_file(filename):
    if filename not in os.listdir(UPLOAD_FOLDER):
        # return jsonify({'error': 'File not found'}), 404
        return jsonify({
            "status": -1,
            "errorCode": 1006,
            "errorMsg": "File not found",
            "resultBody": None
        })
    return send_from_directory(UPLOAD_FOLDER, filename, as_attachment=True)

# 删除文件接口
@static_resource_bp.route('/delete/<filename>', methods=['DELETE'])
def delete_file(filename):
    file_path = os.path.join(UPLOAD_FOLDER, filename)
    if os.path.exists(file_path):
        os.remove(file_path)
        # return jsonify({'message': 'File deleted successfully'}), 200
        return jsonify({
            "status": 1,
            "errorCode": None,
            "errorMsg": None,
            "resultBody": "File deleted successfully"
        })
    else:
        # return jsonify({'error': 'File not found'}), 404
        return jsonify({
            "status": -1,
            "errorCode": 1000,
            "errorMsg": "File not found",
            "resultBody": None
        })

# 展示文件列表接口
@static_resource_bp.route('/files', methods=['GET'])
def list_files():
    files = os.listdir(UPLOAD_FOLDER)
    # return jsonify({'files': files}), 200
    # 获取文件大小及创建时间

    file_info = []
    for file in files:
        file_path = os.path.join(UPLOAD_FOLDER, file)
        file_size = os.path.getsize(file_path)
        file_ctime = os.path.getctime(file_path)
        file_info.append({
            "filename": file,
            "size": file_size,
            "ctime": file_ctime
        })
    return jsonify({
        "status": 1,
        "errorCode": None,
        "errorMsg": None,
        "resultBody": file_info
    })
